# app/schedule_free.py

from flask import Blueprint, request, jsonify, session, abort
from datetime import datetime, timedelta, time
from . import db
from .models import Schedule
from .schedule_mgmt import login_required

free_bp = Blueprint('schedule_free', __name__, url_prefix='/api/schedules')

def daterange(start: datetime.date, end: datetime.date):
    cur = start
    while cur <= end:
        yield cur
        cur += timedelta(days=1)

@free_bp.route('/free', methods=['GET'])
@login_required
def free_slots():
    """
    GET /api/schedules/free?start_date=YYYY-MM-DD&end_date=YYYY-MM-DD
    返回每一天的空闲时间段列表。
    """
    uid = session['user_id']
    sd = request.args.get('start_date')
    ed = request.args.get('end_date')
    if not sd or not ed:
        return jsonify(error="必须提供开始和结束日期"), 400
    try:
        start_d = datetime.strptime(sd, '%Y-%m-%d').date()
        end_d   = datetime.strptime(ed, '%Y-%m-%d').date()
    except:
        return jsonify(error="日期格式错误"), 400
    if start_d > end_d:
        return jsonify(error="结束日期不能早于开始日期"), 400

    result = []
    for day in daterange(start_d, end_d):
        # 取当天所有已排课，按时间排序
        lessons = Schedule.query.filter_by(user_id=uid, one_date=day).order_by(
            Schedule.start_time).all()
        if not lessons:
            result.append({
                "date": day.strftime('%Y-%m-%d'),
                "free": ["当日无排课"]
            })
            continue
        # 构建空闲区间：从 00:00 起，到第一节前；两节之间；最后一节后到 23:59
        intervals = []
        prev_end = time(0,0)
        for les in lessons:
            if les.start_time > prev_end:
                intervals.append(f"{prev_end.strftime('%H:%M')}-{les.start_time.strftime('%H:%M')}")
            prev_end = max(prev_end, les.end_time)
        if prev_end < time(23,59):
            intervals.append(f"{prev_end.strftime('%H:%M')}-23:59")
        result.append({
            "date": day.strftime('%Y-%m-%d'),
            "free": intervals
        })
    return jsonify(result), 200
